package com.itbooking.core.response;

import com.itbooking.util.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

// ResponseBodyAdvice 采用ResponseBodyAdvice技术来实现response的统一格式处理
// 一般用来处理返回值和响应体，做数据的加密和解密，签名等等。
@ControllerAdvice(basePackages = "com.icoding")
public class ResponseBodyAdivce implements ResponseBodyAdvice<Object> {


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof ErrorResult) {
            ErrorResult errorResult = (ErrorResult) o;
            return ServerResponse.createByError(errorResult.getStatus(), errorResult.getMessage());
        } else if (o instanceof String) {
            return JsonUtil.obj2String(ServerResponse.createBySuccess(o));
        }
        return ServerResponse.createBySuccess(o);
    }
}
